// This code is licensed under New BSD Licence. For details see project page at
// http://code.google.com/p/hrissan-cocoa-helpers/source/checkout
#import "SimpleHTTPLoader.h"


@implementation SimpleHTTPLoader

@synthesize delegate;

-(id)initWithDelegate:(id<SimpleHTTPLoaderDelegate>)_delegate {
   if ( (self = [super init]) ) {
	   self.delegate = _delegate;
    }
    return self;
}

-(void)result:(NSMutableData *)_result_data statusCode:(int)_statusCode {
	NSMutableData * da = [[_result_data retain] autorelease];
	result_data = 0;
	conn = 0;
	if( delegate )
		[delegate loader:self result:da statusCode:_statusCode];
	stop_network_indicator();
}

+(NSString *)prepare_parameter:(NSString *)param {
	param = [param stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	param = [param stringByReplacingOccurrencesOfString:@"&" withString:@"%26"];
	return param;
}

-(bool)loading {
	return conn.get() != 0;
}

- (void)cancel_request
{
	if( !conn.get() )
		return;
	[conn.get() cancel];
	[self result:0 statusCode:0];
}

-(void)send_request:(NSURLRequest *)request {
	start_network_indicator();
	[self cancel_request];

	statusCode = 0;
	conn = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
{
	statusCode = [response statusCode];

	long long cl = [response expectedContentLength];
	if( connection == conn.get() )
		result_data = [NSMutableData dataWithCapacity:cl != NSURLResponseUnknownLength ? cl : 8192];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	if( connection == conn.get() )
		[result_data.get() appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	if( connection == conn.get() )
	{
		[self result:result_data.get() statusCode:statusCode];
	}
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	if( connection == conn.get() )
	{
		NSLog(@"connection didFailWithError. Error: %@", error);
		[self result:0 statusCode:0];
	}
}
@end
